package com.base.system.managedBean;

import java.util.List;

import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.operamasks.faces.annotation.Accessible;
import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.Inject;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.annotation.SaveState;
import org.operamasks.faces.annotation.SelectItems;
import org.operamasks.faces.user.util.Browser;

import com.base.commons.SpringBeanHolder;
import com.base.organization.DAPType;
import com.base.organization.DutyType;
import com.base.organization.entity.DepartmentAndPerson;
import com.base.organization.entity.DepartmentalUnit;
import com.base.organization.entity.Employee;
import com.base.organization.service.IDepartmentAndPersonDAO;
import com.base.organization.service.IDepartmentalUnitDAO;
import com.base.organization.service.IPersonnelDao;
import com.base.security.SecurityUserHolder;
import com.base.security.entity.SecurityUser;
import com.base.security.service.SecurityEntityManager;

/**
 * 
 * This managed bean is generated automatically
 */
@ManagedBean(name = "system_editDepAndPersonBean", scope = ManagedBeanScope.REQUEST)
public class EditDepAndPersonBean {
	Log logger = LogFactory.getLog(EditDepAndPersonBean.class);
	private SecurityEntityManager securityEntityManager = SpringBeanHolder
			.getBean("securityEntityManager");
	private IDepartmentAndPersonDAO departmentAndPersonDAO = SpringBeanHolder
			.getBean("departmentAndPersonDAO");
	private IDepartmentalUnitDAO departmentalUnitDAO = SpringBeanHolder
			.getBean("departmentalUnitDAO");
	private IPersonnelDao personDao = SpringBeanHolder.getBean("personDao");
	@Inject
	FacesContext context;
	@Bind(id = "departmentId", attribute = "value")
	private String departmentId;
	@Bind(id = "departmentId_name", attribute = "value")
	private String departmentId_name;
	@SaveState
	private String userId;
	@SaveState
	private String deptId;
	@Accessible
	private SelectItem[] type_items = {
			new SelectItem(DAPType.BELONG.name(), "属于"),
			new SelectItem(DAPType.PARTTIME.name(), "兼任") };
	@Bind(id = "type")
	@SelectItems(source = "#{this.type_items}")
	private String type;
	@Accessible
	private SelectItem[] duty_items = {
			new SelectItem(DutyType.INCHARGE.name(), "负责人"),
			new SelectItem(DutyType.SECRETARY.name(), "秘书"),
			new SelectItem(DutyType.COMMON.name(), "普通员工"),
	// new SelectItem(DutyType.MANAGE.name(), "主管")
	};
	@Bind(id = "duty")
	@SelectItems(source = "#{this.duty_items}")
	private String duty;

	@BeforeRender
	public void beforeRender(boolean isPostback) {
		if (!isPostback) {
			userId = context.getExternalContext().getRequestParameterMap().get(
					"userId");
			deptId = context.getExternalContext().getRequestParameterMap().get(
					"depId");
			if (deptId != null && !"".equals(deptId)) {
				List<DepartmentAndPerson> list = this.securityEntityManager
						.getDepartmentAndPerson(Integer.parseInt(deptId),
								Integer.parseInt(userId));
				if (!list.isEmpty()) {
					DepartmentAndPerson dap = list.get(0);
					departmentId = dap.getDepartmentalUnit()
							.getDepartmentalUnitId().toString();
					departmentId_name = dap.getDepartmentalUnit().getName();
					if (dap.getType() != null)
						type = dap.getType().name();
					if (dap.getDuty() != null)
						duty = dap.getDuty().name();
				}
			}
		}
	}

	@Action(id = "saveSecurityUser")
	public void saveSecurityUser() {
		Integer uid = Integer.parseInt(userId);
		Integer depId = null;
		if (deptId != null && !"".equals(deptId)) {
			depId = Integer.parseInt(deptId);
		} else {
			depId = Integer.parseInt(departmentId);
		}
		List<DepartmentAndPerson> list = this.securityEntityManager
				.getDepartmentAndPerson(depId, uid);
		// System.out.println("得到的dap is:" + list.size());
		DepartmentalUnit departmentalUnit = departmentalUnitDAO.get(Integer
				.parseInt(departmentId));
		SecurityUser user = securityEntityManager.getUserById(String
				.valueOf(uid));
		DepartmentAndPerson dp = null;
		if (list.isEmpty()) {
			dp = new DepartmentAndPerson();
			dp.setDepartmentalUnit(departmentalUnit);
			dp.setEnable(true);
			dp.setPerson(user);
			dp.setType(DAPType.valueOf(type));
			dp.setDuty(DutyType.valueOf(duty));
			dp.setIndexNumber(departmentAndPersonDAO
					.getLastIndexOfDept(departmentalUnit
							.getDepartmentalUnitId()) + 1);
			departmentAndPersonDAO.insert(dp);
			// 员工信息是否生成，如果未生成，此处生成员工信息
			// 生成Employee
			List<Employee> all = personDao.findAllByNamedQuery(
					"person.getEmployeeOfUser", uid);
			if (all != null && all.size() > 0) {
			} else {
				Employee temp = new Employee();
				temp.setUser(user);
				personDao.insert(temp);
			}
		} else {
			dp = list.get(0);
			// 删除
			departmentAndPersonDAO.delete(dp);
			// 再新建
			DepartmentAndPerson temp = new DepartmentAndPerson();
			temp.setDepartmentalUnit(departmentalUnit);
			temp.setEnable(true);
			temp.setPerson(user);
			temp.setDepartmentalUnit(departmentalUnit);
			temp.setType(DAPType.valueOf(type));
			temp.setDuty(DutyType.valueOf(duty));
			temp.setIndexNumber(departmentAndPersonDAO
					.getLastIndexOfDept(departmentalUnit
							.getDepartmentalUnitId()) + 1);
			departmentAndPersonDAO.insert(temp);
		}
		// 重置当前用户的部门
		SecurityUserHolder.reloadDepartments();
		String script = "closeWindow('dep_relation')";
		Browser.execClientScript("window.parent", script);
	}
}
